package com.lin.cli.example;

import lombok.Data;
import picocli.CommandLine;
import picocli.CommandLine.Option;
import picocli.CommandLine.Command;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;

@Command(name = "login", description = "登录", mixinStandardHelpOptions = true)
public class Login implements Callable<Integer> {
    @Option(names = {"-u", "--username"}, description = "用户名")
    String userName;

    // arity 属性来指定每个选项可接受的参数个数
    @Option(names = {"-p", "--password"}, description = "密码", interactive = true, arity = "0..1", required = true)
    String password;

    @Option(names = {"-cp", "--checkPassword"}, description = "校验密码", interactive = true, arity = "0..1", required = true)
    String checkPassword;

    @Override
    public Integer call() throws Exception {
        System.out.println("用户名：" + userName);
        System.out.println("密码：" + password);
        System.out.println("校验密码：" + checkPassword);
        return null;
    }

    public static void main(String[] args) {
        Login login = new Login();
        CommandLine commandLine = new CommandLine(login);
        try {
            commandLine.execute("-u", "admin");
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

//    public static void validateArgs(Class<?> commandClass, String[] args) {
//        Set<String> providedArgs = new HashSet<>(Arrays.asList(args)); // 用户输入的参数
//        StringBuilder missingArgs = new StringBuilder(); // 用于记录缺失参数
//        // 遍历命令类的所有字段
//        Field[] declaredFields = commandClass.getDeclaredFields();
//        for (Field field : declaredFields) {
//            if (field.isAnnotationPresent(Option.class)) { // 检查字段是否有 @Option 注解
//                Option option = field.getAnnotation(Option.class);
//                if (option.required()) { // 如果是必填选项
//                    boolean isProvided = Arrays.stream(option.names())
//                            .anyMatch(providedArgs::contains);
//                    if (!isProvided) {
//                        missingArgs.append(Arrays.toString(option.names()))
//                                .append(" (")
//                                .append(option.description()[0])
//                                .append(")\n");
//                    }
//                }
//            }
//        }
//
//        // 如果有缺失的参数，抛出异常
//        if (missingArgs.length() > 0) {
//            throw new IllegalArgumentException("Missing required arguments:\n" + missingArgs);
//        }
//    }
}
